<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );

/**
 * 公共库
 * @author xuelange
 *
 */
class Common {

	function __get($key)
	{
		$CI = & get_instance();
		return $CI->$key;
	}
	/**
	 * time33 算法
	 * @param $str
	 * @return string
	 */
	public static function time33($str)
	{
		$len = strlen($str);
		$hash = 0;
		for ($i = 0; $i < $len; $i++) {
			$hash = ($hash <<5)+ $hash + ord($str[$i]);
		}
		return sprintf("%u",$hash);
	}

	public static function do_hash($str, $salt) {
		return sha1 ( md5 ( $str ) . $salt );
	}
	
	public static function hash_Validate($source, $salt, $target) {
		return (self::do_hash ( $source, $salt ) == $target);
	}

	/**
	 * 获取一个全局唯一md5值
	 */
	public static function uniqid(){
		return md5(uniqid(microtime(true).mt_rand(0,9), true));
	}
	public static function prf_json($flag, $arr, $paramArr = NULL, $ts = NULL,$is_pri = TRUE,$msg = NULL) {

		$ret = 1;
		if ($flag) {
			$ret = - 1;
		}
		if (! $paramArr) {
			$paramArr = array ();
		}
		if (! $ts) {
			$paramArr ['_rsvd_ts'] = time ();
		} else {
			$paramArr ['_rsvd_ts'] = $ts;
		}
		
		$pri = array_merge(array (
			"ret" => $ret,
			"data" => empty ( $arr ) ? NULL : $arr
		),$paramArr);
		if($msg){
			$pri['msg'] = $msg;
		}
		if($is_pri){
			header("Content-Type: application/json; charset=utf-8");
			echo json_encode ( $pri );
		}else{
			return json_encode ( $pri );
		}
	}

	public function create_uuid($prefix = "") {
		$str = md5 ( uniqid ( mt_rand (), true ) );
		$uuid = substr ( $str, 0, 8 ) . '-';
		$uuid .= substr ( $str, 8, 4 ) . '-';
		$uuid .= substr ( $str, 12, 4 ) . '-';
		$uuid .= substr ( $str, 16, 4 ) . '-';
		$uuid .= substr ( $str, 20, 12 );
		return $prefix . $uuid;
	}
	
	public static function get_file_type($filetype) {
		// $test = "dddd.ddd.txt";
		$arr = explode ( ".", $filetype );
		if (! $arr) {
			// return "文件名称没有后缀名";
			return "";
		}
		$len = count ( $arr );
		return strtolower ( $arr [$len - 1] );
	}
	
	public static function get_file_size($byte) {
		if ($byte < 1024) {
			$unit = "B";
		} else if ($byte < 10240) {
			$byte = self::round_dp ( $byte / 1024, 2 );
			$unit = "KB";
		} else if ($byte < 102400) {
			$byte = self::round_dp ( $byte / 1024, 2 );
			$unit = "KB";
		} else if ($byte < 1048576) {
			$byte = self::round_dp ( $byte / 1024, 2 );
			$unit = "KB";
		} else if ($byte < 10485760) {
			$byte = self::round_dp ( $byte / 1048576, 2 );
			$unit = "MB";
		} else if ($byte < 104857600) {
			$byte = self::round_dp ( $byte / 1048576, 2 );
			$unit = "MB";
		} else if ($byte < 1073741824) {
			$byte = self::round_dp ( $byte / 1048576, 2 );
			$unit = "MB";
		} else {
			$byte = self::round_dp ( $byte / 1073741824, 2 );
			$unit = "GB";
		}
		
		$byte .= $unit;
		return $byte;
	}
	
	public static function round_dp($num, $dp) {
		$sh = pow ( 10, $dp );
		return round(round ( $num * $sh ) / $sh);
	}
	
	public function set_security_init($sec_policy) {
		$value = 11;
		switch ($sec_policy) {
			// 打开次数默认10次
			case "open_counter" :
				$value = 10;
				break;
			// 过期时间为当前打包时间+1天
			case "life_span" :
				$value = time () + 86400;
				break;
			// 文件过期后自动删除
			case "delete" :
				$value = "1";
				break;
			default :
				break;
		}
		return $value;
	}
	
	public function is_Date($string) {
		$patt = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/';
		if (preg_match ( $patt, $string )) {
			return true;
		}
		return false;
	}
	
	/**
	 * 时间段转换为具体时间
	 */
	function slotToSpecific($type){
		$result = 3600;
		switch ($type){
			case 1:
			default:
				$result = 3600;
				break;
			case 2:
				$result = 14400;
				break;
			case 3:
				$result = 86400;
				break;
			case 4:
				$result = 259200;
				break;
			case 5:
				$result = 604800;
				break;
			case 6:
				$result = strtotime("+1 month")-time();
				break;
				
		}
		return $result;
	}
	
	/**
	 * 时间只取小时，向前四舍五入
	 */
	function minuteRound($time){
		$year = (int)substr($time, 0,4);
		$month= (int)substr($time, 5,2);
		$day = (int)substr($time, 8,2);
		$hour = (int)substr($time, 11,2);
		$minute = (int)substr($time, 14,2);
// 		var_dump($minute);
		if($minute>0){
			$hour +=1;
		}
		return mktime($hour, 0, 0, $month, $day, $year);
	}
	
	
	/**
	 * 成功提示函数
	 * @param  [type] $url [跳转地址]
	 * @param  [type] $msg [提示信息]
	 * @return [type]      [description]
	 */
	function success($url, $msg){
		header('Content-Type:text/html;charset=utf-8');
		$url = site_url($url);
		echo "<script type='text/javascript'>alert('$msg');location.href='$url'</script>";
		die;
	}
	
	/**
	 * 错误提示函数
	 * @param  [type] $msg [提示信息]
	 * @return [type]      [description]
	 */
	function error($msg){
		header('Content-Type:text/html;charset=utf-8');
		echo "<script type='text/javascript'>alert('$msg');window.history.back();</script>";
		die;
	}

	/**
	 *
	 * RC4算法
	 * @param $key 密码
	 * @param $str 密文
	 * @return string 解密结果
	 */
	function rc4($key, $str) {
		$s = array();
		for ($i = 0; $i < 256; $i++) {
			$s[$i] = $i;
		}
		$j = 0;
		for ($i = 0; $i < 256; $i++) {
			$j = ($j + $s[$i] + ord($key[$i % strlen($key)])) % 256;
			$x = $s[$i];
			$s[$i] = $s[$j];
			$s[$j] = $x;
		}
		$i = 0;
		$j = 0;
		$res = '';
		for ($y = 0; $y < strlen($str); $y++) {
			$i = ($i + 1) % 256;
			$j = ($j + $s[$i]) % 256;
			$x = $s[$i];
			$s[$i] = $s[$j];
			$s[$j] = $x;
			$res .= $str[$y] ^ chr($s[($s[$i] + $s[$j]) % 256]);
		}
		return $res;
	}
	
	function arrayLevel($arr){
		$al = array(0);
		function aL($arr,&$al,$level=0){
			if(is_array($arr)){
				$level++;
				$al[] = $level;
				foreach($arr as $v){
					aL($v,$al,$level);
				}
			}
		}
		aL($arr,$al);
		return max($al);
	}
	
	function rc4_json($json,$key="wfonline") {
// 		var_dump($json);
		if (ENVIRONMENT == "development") {
			echo $json;
			return;
		}
		$rc = self::rc4($key,$json);
		echo $rc;
// 		return $rc;
	}
	
	/**
	 * 二维数组转为一维数组
	 * @param unknown $arr
	 * @param unknown $key
	 * @return multitype:unknown
	 */
	function array_colum($arr,$key){
		$newArr = array();
		foreach ($arr as $v){
			$newArr[] = $v[$key];
		}
		return $newArr;
	}
	
	/**
	 * 选择策略id
	 * @param unknown $desc
	 * @return number
	 */
	public function selectPolicyId($desc){
		$pid = 1;
		switch ($desc){
			case "open_counter":
			default:
				$pid = 1;
				break;
			case "life_span":
				$pid = 2;
				break;
			case "delete_after_expired":
				$pid = 3;
				break;
			case "access_denied":
				$pid = 4;
				break;
			case "read_pwd":
				$pid = 5;
				break;
		}
		return $pid;
	}
	
	
	/**
	 * 根据策略id获取策略描述
	 * @param unknown $pid 策略id
	 */
	public function selectPolicyDes($pid){
		$desc = "open_counter";
		switch ($pid){
			case 1:
			default:
				$desc = "open_counter";
				break;
			case 2:
				$desc = "life_span";
				break;
			case 3:
				$desc = "delete_after_expired";
				break;
			case 4:
				$desc = "access_denied";
				break;
			case 5:
				$desc = "read_pwd";
				break;
		}
		return $desc;
	}
	
	
	//递归创建目录
	static function create_folder($path) {
		if (! file_exists($path)) {
            mkdir($path, 0777, TRUE);
		}
	}
	
	/**
	 * 通过ip获得城市信息
	 * @param unknown_type $ip
	 */
	static function query_city($ip){
		$res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
		if(empty($res)){
			return false;
		}
		$jsonMatches = array();
		preg_match('#\{.+?\}#', $res, $jsonMatches);
		if(!isset($jsonMatches[0])){
			return false;
		}
		$json = json_decode($jsonMatches[0], true);
		if(isset($json['ret']) && $json['ret'] == 1){
			$json['ip'] = $ip;
			unset($json['ret']);
		}else{
			return false;
		}
		return $json;
	}
	
	/**
	 * 立即进入邮箱
	 * @param strong $mail
	 * @return string
	 */
	static function get_email_url($mail){
		if(!$mail){
			return '';
		}
		$t=explode('@',$mail);
		$t=strtolower($t[1]);
		if($t=='163.com'){
			return 'mail.163.com';
		}else if($t=='vip.163.com'){
			return 'vip.163.com';
		}else if($t=='126.com'){
			return 'mail.126.com';
		}else if($t=='qq.com'||$t=='vip.qq.com'||$t=='foxmail.com'){
			return 'mail.qq.com';
		}else if($t=='gmail.com'){
			return 'mail.google.com';
		}else if($t=='sohu.com'){
			return 'mail.sohu.com';
		}else if($t=='tom.com'){
			return 'mail.tom.com';
		}else if($t=='vip.sina.com'){
			return 'vip.sina.com';
		}else if($t=='sina.com.cn'||$t=='sina.com'){
			return 'mail.sina.com.cn';
		}else if($t=='tom.com'){
			return 'mail.tom.com';
		}else if($t=='yahoo.com.cn'||$t=='yahoo.cn'){
			return 'mail.cn.yahoo.com';
		}else if($t=='tom.com'){
			return 'mail.tom.com';
		}else if($t=='yeah.net'){
			return 'www.yeah.net';
		}else if($t=='21cn.com'){
			return 'mail.21cn.com';
		}else if($t=='hotmail.com'){
			return 'www.hotmail.com';
		}else if($t=='sogou.com'){
			return 'mail.sogou.com';
		}else if($t=='188.com'){
			return 'www.188.com';
		}else if($t=='139.com'){
			return 'mail.10086.cn';
		}else if($t=='189.cn'){
			return 'webmail15.189.cn/webmail';
		}else if($t=='wo.com.cn'){
			return 'mail.wo.com.cn/smsmail';
		}else if($t=='139.com'){
			return 'mail.10086.cn';
		}else {
			return 'mail.'.$t;
		}
	}

	/**
	 *
	 * 兼容低版本array_column函数
	 * @param $input
	 * @param $columnKey
	 * @param null $indexKey
	 * @return array
	 */
	public static function array_column($input, $columnKey, $indexKey=null){
		if(empty($input) || !is_array($input))return array();
		if(!function_exists('array_column')){
			$columnKeyIsNumber  = (is_numeric($columnKey))?true:false;
			$indexKeyIsNull            = (is_null($indexKey))?true :false;
			$indexKeyIsNumber     = (is_numeric($indexKey))?true:false;
			$result                         = array();
			foreach((array)$input as $key=>$row){
				if($columnKeyIsNumber){
					$tmp= array_slice($row, $columnKey, 1);
					$tmp= (is_array($tmp) && !empty($tmp))?current($tmp):null;
				}else{
					$tmp= isset($row[$columnKey])?$row[$columnKey]:null;
				}
				if(!$indexKeyIsNull){
					if($indexKeyIsNumber){
						$key = array_slice($row, $indexKey, 1);
						$key = (is_array($key) && !empty($key))?current($key):null;
						$key = is_null($key)?0:$key;
					}else{
						$key = isset($row[$indexKey])?$row[$indexKey]:0;
					}
				}
				$result[$key] = $tmp;
			}
			return $result;
		}else{
			return array_column($input, $columnKey, $indexKey);
		}
	}

	/**
	 * 数组键值填充
	 * @param $array 数组
	 * @param string $prefix 前填充
	 * @param string $suffix 后填充
	 * @return array
	 */
	public static function array_key_fill($array,$prefix="",$suffix="")
	{
		$result = array();
		foreach($array as $k=>$v)
		{
			$key = $prefix.$k.$suffix;
			$result[$key]=$v;
		}
		return $result;
	}

	/**
	 * 搜索二维数组
	 * @param $array 数组
	 * @param $col 字段
	 * @param $value 字段的条件值
	 * @param bool $limit 获取多少条
	 * @return array|null
	 */
	public static function array_find_rows($array,$col,$value,$limit=false)
	{
		if(empty($array))return null;
		$find=array();
		$find_count=0;
		foreach($array as $k=>$v)
		{
			if(isset($v[$col]) && $v[$col]==$value)
			{
				$find[] = $v;
				$find_count++;
				if($find_count===$limit)
				{
					break;
				}
			}
		}
		if(empty($find))
		{
			return null;
		}
		return $limit==1?$find[0]:$find;
	}

	/**
	 * 二维数组去重
	 * @param $array
	 * @param $key
	 * @return array
	 *
		$details = array(
			0 => array("id"=>"1", "name"=>"Mike",    "num"=>"9876543210"),
			1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
			2 => array("id"=>"1", "name"=>"Mathew",  "num"=>"784581254"),
		);
		$details = unique_multidim_array($details,'id');

		Out:
			$details = array(
				0 => array("id"=>"1","name"=>"Mike","num"=>"9876543210"),
				1 => array("id"=>"2","name"=>"Carissa","num"=>"08548596258"),
			);
	 */
	public static function unique_multidim_array($array, $key) {
		$temp_array = array();
		$i = 0;
		$key_array = array();

		foreach($array as $val) {
			if (!in_array($val[$key], $key_array)) {
				$key_array[$i] = $val[$key];
				$temp_array[$i] = $val;
			}
			$i++;
		}
		return $temp_array;
	}

	/**
	 * 获取文件mime类型
	 * @param $file
	 */
	public static function get_mime_type($file)
	{
		$finfo = finfo_open(FILEINFO_MIME);
		$mime_type = finfo_file($finfo, $file);
		finfo_close($finfo);
		$new=preg_match('/([^;]+);?.*$/',$mime_type,$match);
		if($new)
		{
			$mime_type=trim($match[1]);
		}
		return $mime_type;
	}

	/**
	 * 生成随机数字验证码
	 * @param int $length
	 * @return string
	 */
	public static function random_number($length=4)
	{
		$num="";
		for($a=0;$a<$length;$a++)
		{
			$num .=rand(0,9);
		}
		return $num;
	}

	public static function console($data,$append=FALSE)
	{
		if(is_array($data))
		{
			$data = json_encode($data);
		}
		$split = PHP_EOL.PHP_EOL."=======================  控制台 ".date("Y-m-d H:i:s")." START ============================".PHP_EOL;
		$split2 = PHP_EOL."=======================  控制台 ".date("Y-m-d H:i:s")." END   ============================".PHP_EOL.PHP_EOL;
		$echo =$split.$data.$split2;
		if($append)
		{
			file_put_contents("console.txt",$echo,FILE_APPEND);
		}
		else
		{
			file_put_contents("console.txt",$echo);
		}
	}


	/**
	 * 标准的ajax返回操作结果
	 * @param int $code 错误代码 0时为操作成功
	 * @param string $msg 错误信息 值为NULL时自动读取语言包的信息
	 * @param array $extraParams 额外的返回参数
	 * @param array $extra_params_in 额外的参数在结构体同级还是下一级 TRUE则挂在extra_params下面 FALSE则与error_code等基本参数同一级
	 * @param string $type
	 * @return array
	 */
	public static function ajax_return($code = 0, $msg = NULL,$extra_params=NULL,$extra_params_in=TRUE,$type='JSON')
	{
		$CI=&get_instance();

		//跨域处理
		$arrow = config_item("cors_host");
		$origin = $CI->input->server("HTTP_ORIGIN");

		if(in_array($origin,$arrow)){
			header('Access-Control-Allow-Origin:'.$origin);
			// 响应类型
			header('Access-Control-Allow-Methods:GET,POST,OPTIONS,PUT,DELETE');
			//header('Access-Control-Max-Age:60');
			// 响应头设置
			header('Access-Control-Allow-Headers:X-Requested-With,Content-type');
			header('Access-Control-Allow-Credentials:true');
			if($CI->input->server('REQUEST_METHOD')=="OPTIONS"){
				exit();
			}
		}

		//如果code是service对象则从service对象里面去错误信息
		if(is_object($code))
		{
			if(method_exists($code,"get_error"))
			{
				$error = $code->get_error();
				$code = $error['code'];
				$msg = $msg===NULL?$error['msg']:$msg;
				$extra_params = $extra_params===NULL?$error['info']:$extra_params;
			}
			else
			{
				$code = 1009;
			}
		}
		$data = array(
			'error_code'   => $code,
			'message'     => empty($msg)?self::get_error_message($code):$msg,
			'success'	  => $code===0?	TRUE:FALSE,
			'extra_params'=> NULL
		);
		if($extra_params_in===TRUE)
		{
			$data['extra_params'] = empty($extra_params)?NULL:$extra_params;
		}
		else if(!empty($extra_params) && is_array($extra_params))
		{
			$data = array_merge($data,$extra_params);
		}
		switch($type)
		{
			case 'JSON':
				exit(json_encode($data, JSON_UNESCAPED_UNICODE));
				//exit(json_encode($data));
				break;
			case 'RETURN':
				return $data;
				break;
		}
	}

	/**
	 * 通过错误代码获取提示信息
	 * @param $code
	 * @return string
	 */
	public static function get_error_message($code,$format_arg=array())
	{
		$CI = & get_instance();
		if($code>=5000 && $code<=5999)
		{
			$CI->load->language('user');
		}
		else if($code>=6000 && $code<=6999)
		{
			$CI->load->language('sender');
		}
		else if($code>=7000 && $code<=7999)
		{
			$CI->load->language('files');
		}
		$msg =  $CI->lang->line("error_".$code);
		//格式
		if(!empty($format_arg))
		{
			$args =array_merge(array($msg),$format_arg);
			$msg = call_user_func_array("sprintf",$args);
		}
		return $msg;
	}


	public static function format_byte($byte)
	{
		//小于1K
		if($byte<1024)
		{
			$b = $byte;
			$unit = "B";
		}
		//小于1MB
		else if ($byte < 1048576)
		{
			$b = round(sprintf("%f",$byte / 1024),2);
			$unit = "KB";
		}
		else if ($byte < 1073741824)
		{
			$b = round(sprintf("%f",$byte / 1048576),2);
			$unit = "MB";
		}
		else if($byte < 1099511627776)
		{
			$b = round(sprintf("%f",$byte/1073741824),2);
			$unit = "GB";
		}
		else
		{
			$b = round(sprintf("%f",$byte/1099511627776),2);
			$unit = "TB";
		}
		$b .= $unit;
		return $b;
	}

	/**
	 * 格式化秒
	 * @param $second
	 * @return float|string
	 */
	public static function format_second($second)
	{
		$CI = & get_instance();
		$val = $second;
		$unit = $CI->lang->line("second");
		if($second>3600)
		{
			$val = round($second/3600);
			$unit =$CI->lang->line("hour");
		}
		else if($second>60)
		{
			$val = round($second/60);
			$unit =$CI->lang->line("minute");
		}
		$val .= $unit;
		return $val;
	}

	public static function show_message($msg,$title="",$type="success",$url="/",$time=5)
	{
		$CI = & get_instance();
		$data=array(
			"title"=>$title,
			"type" =>$type,
			"msg" =>$msg,
			"url" =>$url,
			"time"=>$time
		);
		$CI->template->view("common/message.tpl",$data);
	}
	//隐藏手机中间部分
	public static function hide_tel($phone)
	{
		return preg_replace("/([0-9]{3})[0-9]{4}([0-9]{4})/", "\$1****\$2", $phone);
	}
	//隐藏邮件中间部分
	public static function hide_email($email)
	{
		$n = strpos($email,'@');
		if($n>6){
			$email = substr_replace($email,"****",2,4);
		}elseif($n>4){
			$email = substr_replace($email,"***",2,3);
		}
		elseif($n>2)
		{
			$email = substr_replace($email,"**",1,2);
		}
		return $email;
	}

	/**
	 * 拼接字段
	 * @param $select_fields 字段
	 * @param $fields 要拼接的字段
	 * @param string $prefix 拼接的连接符
	 */
	public static function parse_fields(&$select_fields,$fields,$prefix="")
	{
		if(empty($fields))
		{
			return;
		}
		if(!is_array($fields))
		{
			$fields = explode(",",$fields);
		}
		foreach($fields as $k=>$v)
		{
			$select_fields[]=$prefix.$v;
		}
	}

	/**
	 * 拼接下载地址
	 * @param array $params 拼接的参数
	 */
	public static function source_link($params=array()) {
		if (empty($params)) return;

		$url = "/d?" . http_build_query($params);

		return $url;
	}

	/**
	 * 获取session里面已经存在的下载地址，防止同一用户同一终端产生过多的下载地址
	 * @param $id
	 * @param $flag 标识
	 * @return mixed
	 */
	public static function download_link($id, $flag = "") {
		if (empty($id) || empty($flag)) return;

		$CI = &get_instance();
		$download_exp = $CI->config->item("download_expire_time");
		$find = $id . "_" . $flag;
		$sess_key = "__DOWNLOAD__";
		$sess_data = $CI->session->userdata($sess_key);
		if (!empty($sess_data)) {
			$new_sess_data = array();
			//清除过期的link
			foreach ($sess_data as $k => $v) {
				if (time() - $v['time'] <= $download_exp) {
					$new_sess_data[$k] = $v;
				}
			}
		}

		if (isset($new_sess_data[$find])) {
			$new_sess_data[$find]['time'] = time();
		} else {
			$new_sess_data[$find] = array(
				"time" => time(),
				"link_id" => self::uniqid()
			);
		}
		$CI->session->set_userdata($sess_key, $new_sess_data);
		return $new_sess_data[$find]['link_id'];
	}
}
